<template>
  <div class="simple-container">
    <!-- 简约背景图 -->
    <div class="simple-background"></div>

    <!-- 内容区域 -->
    <div class="simple-content">
      <!-- 注册框 -->
      <div class="simple-login-box">
        <h3>用户注册</h3>

        <el-form
            :model="form"
            :rules="rules"
            ref="registerForm"
            @submit.prevent="handleRegister"
        >
          <el-form-item prop="username">
            <el-input
                v-model="form.username"
                placeholder="请输入用户名"
                prefix-icon="User"
                @blur="checkUsername"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="form.password"
                type="password"
                placeholder="请输入密码（至少6位）"
                prefix-icon="Lock"
                show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
                v-model="form.confirmPassword"
                type="password"
                placeholder="请确认密码"
                prefix-icon="Lock"
                show-password
            />
          </el-form-item>

          <el-form-item prop="phone">
            <el-input
                v-model="form.phone"
                placeholder="请输入手机号"
                prefix-icon="Phone"
            />
          </el-form-item>

          <el-form-item prop="email">
            <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item prop="isStudent">
            <el-checkbox v-model="form.isStudent">
              我是学生
            </el-checkbox>
          </el-form-item>

          <el-form-item
              prop="studentCertNo"
              v-if="form.isStudent"
          >
            <el-input
                v-model="form.studentCertNo"
                placeholder="请输入学生证号"
                prefix-icon="Document"
            />
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                native-type="submit"
                class="simple-submit-btn"
                :loading="loading"
            >
              立即注册
            </el-button>
          </el-form-item>
        </el-form>

        <div class="simple-options">
          <span>已有账号？</span>
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </div>

      <!-- 页脚 -->
      <div class="simple-footer">
        <p>Copyright © 2024-2025.版权所有 请根据本标准发布的信息</p>
      </div>

      <!-- 管理员登录链接 -->
      <div class="simple-admin-login">
        <el-link type="info" @click="showAdminDialog">管理员登录</el-link>
      </div>
    </div>

    <!-- 管理员登录对话框（保持原有） -->
    <el-dialog v-model="adminDialogVisible" title="管理员登录" width="30%">
      <el-form :model="adminForm" :rules="adminRules" ref="adminFormRef">
        <el-form-item prop="password">
          <el-input
              v-model="adminForm.password"
              type="password"
              placeholder="请输入管理员密码"
              show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="adminLogin">登录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const registerForm = ref(null)
const loading = ref(false)
const usernameExists = ref(false)
const adminDialogVisible = ref(false)

const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  isStudent: false,
  studentCertNo: ''
})

const adminForm = ref({ password: '' })
const adminFormRef = ref(null)

const validateUsername = (rule, value, callback) => {
  if (usernameExists.value) {
    callback(new Error('用户名已存在'))
  } else {
    callback()
  }
}

const validatePassword = (rule, value, callback) => {
  if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { validator: validateUsername, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    {
      type: 'email',
      message: '请输入有效的邮箱地址',
      trigger: 'blur'
    }
  ],
  studentCertNo: [
    {
      required: true,
      message: '学生证号不能为空',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.value.isStudent && !value) {
          callback(new Error('学生证号不能为空'))
        } else {
          callback()
        }
      }
    }
  ]
}

const adminRules = {
  password: [
    { required: true, message: '请输入管理员密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

const checkUsername = async () => {
  if (!form.value.username) return
  try {
    const response = await axios.get(BASE_URL+'/user/check', {
      params: { username: form.value.username }
    })
    usernameExists.value = response.data.exists
  } catch (error) {
    console.error(error)
  }
}

const handleRegister = async () => {
  try {
    await registerForm.value.validate()
    loading.value = true

    const payload = {
      username: form.value.username,
      password: form.value.password,
      phone: form.value.phone,
      email: form.value.email,
      is_student: form.value.isStudent,
      student_cert_no: form.value.studentCertNo
    }

    const response = await axios.post(BASE_URL+'/user/reg', payload)

    if (response.data.state === 200) {
      ElMessage.success('注册成功')
      router.push('/login')
    } else {
      ElMessage.error(response.data.message || '注册失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  } finally {
    loading.value = false
  }
}

const showAdminDialog = () => {
  adminDialogVisible.value = true;
};

const adminLogin = async () => {
  try {
    const valid = await adminFormRef.value.validate();
    if (valid) {
      const response = await axios.post(BASE_URL+'/admin/login', {
        password: adminForm.value.password
      });

      if (response.data.state === 200) {
        localStorage.setItem('adminToken', response.data.data.token);
        router.push('/admin/dashboard');
        ElMessage.success('管理员登录成功');
      } else {
        ElMessage.error(response.data.msg);
      }
    }
  } catch (error) {
    ElMessage.error('登录失败');
  }
};

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.simple-container {
  display: flex;
  min-height: 100vh;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  position: relative;
}

.simple-background {
  position: fixed;
  top: 10%;
  left: 0;
  width: 100%;
  height: 80%;
  background-image: url('@/assets/loginpicture.png');
  background-size: cover;
  background-position: center;
  opacity: 0.7;
  z-index: 0;
}

.simple-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding-right: 10%;
}

.simple-login-box {
  width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-top: 10vh;
  margin-bottom: 10vh;
  z-index: 1;
}

.simple-login-box h3 {
  text-align: center;
  margin-bottom: 25px;
  font-size: 18px;
  color: #333;
}

.simple-input :deep(.el-input__inner) {
  height: 48px;
  padding-left: 40px;
}

.simple-submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}

.simple-options {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  gap: 8px;
  color: #606266;
}

.simple-footer {
  margin-top: auto;
  text-align: center;
  font-size: 12px;
  color: #888;
  width: 100%;
  padding-bottom: 20px;
}

.simple-admin-login {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

@media (max-width: 768px) {
  .simple-content {
    padding: 20px;
    align-items: center;
  }

  .simple-login-box {
    width: 100%;
    padding: 20px;
    margin-top: 5vh;
    margin-bottom: 5vh;
  }

  .simple-background {
    top: 5%;
    height: 90%;
  }
}
</style>